package com.longxiao.service.message;

import aQute.libg.tuple.Pair;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.TimeZoneRegistry;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.PartStat;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.parameter.Rsvp;
import net.fortuna.ical4j.model.property.*;
import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.util.UidGenerator;
import net.fortuna.ical4j.model.Calendar;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class EmailSender {

    public static void main(String[] args) throws ParseException {
        List<Pair<String, String>> reqs = new ArrayList<Pair<String, String>>();
        reqs.add(new Pair("ouxuesen@le.com", "oxs"));

//        java.util.Calendar cal = java.util.Calendar.getInstance();
//        cal.set(java.util.Calendar.YEAR, 2017);
//        cal.set(java.util.Calendar.MONTH, 5);
//        cal.set(java.util.Calendar.DAY_OF_YEAR, 28);
//        cal.set(java.util.Calendar.HOUR_OF_DAY, 14);
//        cal.set(java.util.Calendar.MINUTE, 00);
//        cal.set(java.util.Calendar.SECOND, 00);
        //
        //
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = sdf.parse("2017-05-26 19:00:00");
        Date endTime = sdf.parse("2017-05-26 20:00:00");
        System.out.print(new Date().toString());
        try {
            sendEventEmail(reqs, startTime, endTime, "龙校在线教育", "龙校在线教育老是端激活链接", "http://www.longxiao.com/code/oxs");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void sendEventEmail(List<Pair<String, String>> reqs, Date startTime, Date endTime,
                                      String location, String name, String content) throws IOException, IllegalArgumentException {
        System.out.println("startTime:" + startTime + " endTime:" + endTime + " location:" + location + " name:" + name + " content:" + content);
        if (reqs == null || reqs.isEmpty()) {
            throw new IllegalArgumentException("Required participant should not be empty!");
        }

        DateTime start = new DateTime(startTime);
        DateTime end = new DateTime(endTime);
        VEvent meeting = new VEvent(start, end, name);
        TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
        // 设置时区
        TimeZone timezone = registry.getTimeZone("Asia/Shanghai");
        VTimeZone tz = timezone.getVTimeZone();
        meeting.getProperties().add(tz.getTimeZoneId());
        meeting.getProperties().add(new Location(location));
        meeting.getProperties().add(new Summary(name));
        meeting.getProperties().add(new Description(content));

        // 设置uid
        UidGenerator ug;
        Uid uid;
        ug = new UidGenerator("uidGen");
        uid = ug.generateUid();
        meeting.getProperties().add(uid);
        List<String> tos = new ArrayList<String>();
        for (Pair<String, String> participant : reqs) {
            Attendee attendee = new Attendee(URI.create("mailto:" + participant.getFirst()));
            attendee.getParameters().add(Role.REQ_PARTICIPANT);
            attendee.getParameters().add(PartStat.NEEDS_ACTION);
            attendee.getParameters().add(Rsvp.TRUE);
            attendee.getParameters().add(new Cn(participant.getSecond()));
            meeting.getProperties().add(attendee);
            tos.add(participant.getFirst());
        }

//        if (opts != null && !opts.isEmpty()) {
//            for (Pair<String, String> participant : opts) {
//                Attendee attendee = new Attendee(URI.create("mailto:" + participant.getFirst()));
//                attendee.getParameters().add(Role.OPT_PARTICIPANT);
//                attendee.getParameters().add(new Cn(participant.getSecond()));
//                meeting.getProperties().add(attendee);
//                tos.add(participant.getFirst());
//            }
//        }

        Calendar icsCalendar = new Calendar();
        icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
        icsCalendar.getProperties().add(Version.VERSION_2_0);
        icsCalendar.getProperties().add(Method.REQUEST);
        icsCalendar.getComponents().add(meeting);

        CalendarOutputter co = new CalendarOutputter(false);
        Writer wtr = new StringWriter();
        co.output(icsCalendar, wtr);
        String mailContent = wtr.toString();

        sendEmail(tos, name, mailContent);
    }


    public static void sendEmail(List<String> tos, String subject, String content) {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.user", "18610138389@163.com");
        properties.put("mail.smtp.host", "smtp.163.com");
        // properties.put("mail.smtp.port", "xxx");
        properties.put("mail.smtp.auth", "true");

        final String username = "18610138389@163.com";
        final String password = "HOUhw0099@11";
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };

        Transport transport = null;

        try {
            Session session = Session.getDefaultInstance(properties,
                    authenticator);
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setSubject(subject);

            for (String to : tos) {
                mimeMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
            }

            mimeMessage.setFrom(new InternetAddress("18610138389@163.com"));

            mimeMessage.setContent(content,"text/calendar;method=REQUEST;charset=UTF-8");

            transport = session.getTransport();
            transport.connect(username, password);
            transport.sendMessage(mimeMessage, mimeMessage.getRecipients(javax.mail.Message.RecipientType.TO));
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (transport != null)
                try {
                    transport.close();
                } catch (MessagingException logOrIgnore) {

                }
        }
    }
}